package com.fintech.pangu.upms.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.google.common.collect.Lists;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Description:
 */
@Configuration
public class MybatisPlusConfig {

    private static final String SYSTEM_TENANT_ID = "tenant_id";

    private static final List<String> IGNORE_TENANT_TABLES = Lists.newArrayList("sys_user","sys_tenant","sys_permission","sys_view","sys_user_tenant");

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 最大单页限制数量，默认 500 条，小于 0 如 -1 不受限制;
        paginationInterceptor.setLimit(-1);


        // SQL解析处理拦截：增加租户处理回调。
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId(boolean where) {
                String tenantId = MultiTenantUtil.get();
                if (StringUtils.isEmpty(tenantId)){
                    throw new RuntimeException("tenantId is null.");
                }
                return new StringValue(tenantId);
            }

            @Override
            public String getTenantIdColumn() {
                return SYSTEM_TENANT_ID;
            }

            @Override
            public boolean doTableFilter(String tableName) {
                return IGNORE_TENANT_TABLES.stream().anyMatch((t) -> t.equalsIgnoreCase(tableName));
            }
        });
        paginationInterceptor.setSqlParserList(Lists.newArrayList(tenantSqlParser));
        return paginationInterceptor;
    }
}
